package database;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MySQLReceptDAO implements ReceptDAO {
	
	private Connector conn = null;
	private ResultSet rs = null;

	public MySQLReceptDAO() throws DALException {
		conn = new Connector();
	}

	public ReceptDTO getRecept(int receptId) throws DALException {
		ReceptDTO recept = null;
		String query = "SELECT * FROM recept WHERE receptId = " + receptId + ";";
		rs = conn.doQuery(query);
		try {
			if (!rs.first()) {
				throw new DALException("Recept " + receptId + "findes ikke");
			}
			recept = new ReceptDTO(rs.getInt(1), rs.getString(2));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return recept;
	}

	public ArrayList<ReceptDTO> getReceptList() throws DALException {
		ArrayList<ReceptDTO> receptList = new ArrayList<ReceptDTO>();
		String query = "SELECT * FROM recept";
		rs = conn.doQuery(query);
		try {
			while (rs.next()) {
				receptList.add(new ReceptDTO(rs.getInt(1), rs.getString(2)));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return receptList;
	}

	public List<ReceptDTO> getReceptList(int first, int count) throws DALException {
		List<ReceptDTO> receptList = new ArrayList<ReceptDTO>();
		String query = "SELECT * FROM recept LIMIT " + first + "," + count;
		rs = conn.doQuery(query);
		try {
			while (rs.next()) {
				receptList.add(new ReceptDTO(rs.getInt(1), rs.getString(2)));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return receptList;
	}

	public int getCount() throws DALException {
		rs = conn.doQuery("SELECT COUNT(receptId) FROM recept");
		try {
			if (rs.next())
				return rs.getInt(1);
			else
				return 0;
		} catch (SQLException e) {
			e.printStackTrace();
			return 0;
		}
	}

	public void createRecept(ReceptDTO recept) throws DALException {
		conn.doUpdate("INSERT INTO recept(receptId, receptNavn) VALUES ("
				+ recept.getReceptId() + ",'"
				+ recept.getReceptNavn() + "');");
	}

	public void createRecept(String receptNavn) throws DALException {
		conn.doUpdate("INSERT INTO recept(receptId, receptNavn) VALUES ("
				+ "NULL" + ",'"
				+ receptNavn + "');");
	}

	public void updateRecept(ReceptDTO recept) throws DALException {
		conn.doUpdate("UPDATE recept SET  receptId = '" + recept.getReceptId()
				+ "', receptNavn =  '" + recept.getReceptNavn()
				+ "' WHERE receptId = " + recept.getReceptId());
	}
}
